package cn.xiuxian.rsmd;


import cn.xiuxian.util.JdbcUtil;
import com.mysql.cj.util.StringUtils;

import javax.swing.plaf.nimbus.State;
import java.sql.*;
import java.util.Scanner;

//手写MySQL客户端
public class Client {
    public static void main(String[] args) {

        start();
    }

    public  static   void start(){
        StringBuilder stringBuilder = new StringBuilder();
        Scanner scanner = new Scanner(System.in);
        System.out.print("mysql>");
        while (true){
            String sql = scanner.nextLine();
            stringBuilder.append(sql+" ");
            if (sql.endsWith(";")){
//                System.out.println(stringBuilder);
                execute(stringBuilder.deleteCharAt(stringBuilder.length()-2).toString().trim());
                stringBuilder.delete(0,stringBuilder.length());
                System.out.print("mysql>");
            }else {
                System.out.print("     >");
            }
        }
    }

    private static void execute(String sql) {
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;

        try {
            connection = JdbcUtil.getConnection();
            statement = connection.createStatement();

            boolean flag = statement.execute(sql);

            if(flag){
                //DQL
                resultSet = statement.getResultSet();
                ResultSetMetaData rsmd = resultSet.getMetaData();
                int columnCount = rsmd.getColumnCount();
                for (int i = 1; i <= columnCount; i++) {
                    System.out.printf("%-20s",rsmd.getColumnName(i));
                }

                System.out.println("");
                int  rows = 0;
                while (resultSet.next()){
                    for (int i = 1; i <= columnCount; i++) {
                        System.out.printf("%-20s",resultSet.getObject(i));
                    }
                    System.out.println();
                   ++ rows ;
                }

                System.out.println(rows+" rows in set (0.00 sec)");
            }else {
                //DML  DDL
                int rows = statement.getUpdateCount();
                System.out.println("Query OK, "+rows+" rows affected (0.05 sec)");
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JdbcUtil.closeConnection(connection,statement,resultSet);
        }
    }
}
